export default{
  namespaced:true,
  state(){
    return{
      // 购物车的数组，用来存储购物车中每个商品的信息对象
      // 每个商品的信息对象，都包含如下 6 个属性：
      // { goods_id, goods_name, goods_price, goods_count,goods_small_logo, goods_state }
      cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
    }
    
  },
  mutations:{
    //将商品添加到购物车
    addtoCart(state,goods){
    const cartItem=  state.cart.find(item=>{
        item.goods_id === goods.goods_id
      })
      if(!cartItem){
        state.cart.push(goods)
      }else{
        cartItem.goods_count ++
      }
      
      this.commit('m_cart/saveCartInfo')
    },
    //本地持久化
    saveCartInfo(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //修改勾选状态
    radioChangeState(state,goods){
      const findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
      findResult.goods_state = goods.goods_state
      this.commit('m_cart/saveCartInfo')
    },
    //修改商品数量
    goodsCountChange(state,goods){
      const findResult = state.cart.find(item=>item.goods_id === goods.goods_id)
      findResult.goods_count = goods.goods_count
      this.commit('m_cart/saveCartInfo')
    },
    //左滑删除商品
    deleteGoods(state,goods_id){
      //过滤出没有被删除的商品，重新赋值给cart
      state.cart = state.cart.filter(item=>item.goods_id!==goods_id)
      //再更新本地
      this.commit('m_cart/saveCartInfo')
    },
    allChecked(state,flag){
      state.cart.forEach(item=>item.goods_state = flag)
      //再更新本地
      this.commit('m_cart/saveCartInfo')
    }
    
  },
  getters:{
    //统计购物车一共加入了多少商品
    total(state){
      // let sum = 0
      // state.cart.forEach(item=>sum+=item.goods_count)
      // return sum
      return state.cart.reduce((sum,item)=>sum+=item.goods_count,0)
    },
    checkedCount(state){
     return state.cart.filter(item=>item.goods_state===true).reduce((sum,item)=>sum+=item.goods_count,0)
    },
    checkedTotalCount(state){
      return state.cart.filter(item=>item.goods_state===true).reduce((sum,item)=>sum+item.goods_price*item.goods_count,0).toFixed(2)
    }
  } 
}